package com.example.learn;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText mobileEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mobileEditText = findViewById(R.id.mobileEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);

        loginButton.setOnClickListener(view -> {
            HttpParams httpParams = new HttpParams();
            httpParams.put("mobile", mobileEditText.getText().toString());
            httpParams.put("password", passwordEditText.getText().toString());
            OkGo.<String>post(Common.API_URL + "base/login/").tag(this).params(httpParams).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    String data = response.body();
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        String code = jsonObject.getString("code");
                        if (!code.equals("1")) {
                            String msg = jsonObject.getString("msg");
                            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String token = jsonObject.getString("data");
                        MainActivity.editor.putString("token", token).apply();
                        Toast.makeText(LoginActivity.this, "登录成功~", Toast.LENGTH_SHORT).show();
                        //更新okgo的公共参数
                        HttpParams httpParams = new HttpParams();
                        httpParams.put("token", MainActivity.sharedPreferences.getString("token", ""));
                        OkGo.getInstance().addCommonParams(httpParams).init(getApplication());
                        MainActivity.isLogin = true;
                        finish();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        });

    }

}
